package com.canbot.u05.activity.vipguide;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.VipPersonMapData;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 贵宾任务管理（列表）
 */
public class VipGuideTaskManageActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private ViewPager viewPager;

        private Dialog dialogLoading;

        private List<VipPersonMapData> list = new ArrayList<>();

        private int nowIndex;

        public static boolean isShow = false;

        private Button deletebutton;

        private int delIndex;

        private List<VipPersonMapData> finalPersonData2List;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_vip_guide_task_manage);
                deletebutton = ((Button) findViewById(R.id.ok_btn));
                deletebutton.setOnClickListener(this);
                viewPager = (ViewPager) findViewById(R.id.vp_content_action);
                getDate();
                playSound();
                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int i, float v, int i1) {
                        }

                        @Override
                        public void onPageSelected(int i) {
                                nowIndex = i;
                        }

                        @Override
                        public void onPageScrollStateChanged(int i) {

                        }
                });
        }


        private void playSound(){

                String[] voices = {"u05_scrw_001.wav", "u05_scrw_002.wav", "u05_scrw_003.wav"};
                int index = (int) (Math.random() * voices.length);

                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.VIP_GUIDE_DIR + voices[index]);
        }
        @Override
        protected void onResume() {
                super.onResume();
        }

        private void getDate() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("vipType", "queryAllRoute");
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST +
                        ":7755/" + "routevipGuide", hashMap, new OkHttpUtils.OkHttpCallBack() {

                        @Override
                        public void onSuccess(String result) {
                                JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                                if (jsonResponse.getRc()==0) {
                                        String resultData = jsonResponse.getResult().toString();
                                        Logger.e("VipGuideTaskManageActivity", "resultData" + resultData);
                                        list = JSON.parseArray(resultData, VipPersonMapData.class);
                                        Logger.e("VipGuideTaskManageActivity", "list" + list);
                                        if (list!=null && list.size()> 0)  {
                                                runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                                cancelDialog();
                                                                viewPager.setAdapter(pagerAdapter);
                                                        }
                                                });
                                               return;
                                        }
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        cancelDialog();
                                                        startActivity(new Intent(VipGuideTaskManageActivity.this, VipNoFaceActivity.class)
                                                                .putExtra("isTask", "isTask"));
                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                Logger.e("VipGuideTaskManageActivity", "onFailure" + "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                cancelDialog();
                                                ToastTools.newInstance(VipGuideTaskManageActivity.this).showText(getString(R.string.network_request_failed));
                                        }
                                });
                        }
                });
        }

        public void vipTaskback(View view) {
                finish();
        }

        private PagerAdapter pagerAdapter = new PagerAdapter() {
                @Override
                public int getCount() {

                        if (list == null || list.size() == 0) {
                                return 0;
                        }
                        else {
                                return list.size() / 6 + list.size() % 6 > 0 ? 1 : 0;
                        }
                }

                @Override
                public boolean isViewFromObject(View view, Object o) {
                        return view == o;
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView((View) object);
                }

                @Override
                public Object instantiateItem(ViewGroup container, final int position) {
                        LayoutInflater inflater = LayoutInflater.from(container.getContext());
                        View view = inflater.inflate(R.layout.fragment_action_adapter, container, false);
                        GridView mGridView = (GridView) view.findViewById(R.id.gv_content_action);


                        Logger.e("VipGuideTaskManageActivity", "personData2List" + list.toString());
                        List<VipPersonMapData> personData2List = null;
                        for (int i = 0; i < getCount(); i++) {
                                if (i == position) {
                                        personData2List = list.subList(i * 6, i * 6 + 6 > list.size() ? list.size() : i * 6 + 6);
                                }
                        }
                        VipGuideTaskAdapter vipGuideTaskAdapter = new VipGuideTaskAdapter(getBaseContext(), personData2List);
                        mGridView.setAdapter(vipGuideTaskAdapter);


                        finalPersonData2List = personData2List;

                        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                                        startActivity(new Intent(VipGuideTaskManageActivity.this, VipGuideTaskActivity.class)
                                        .putExtra("identification", finalPersonData2List.get(i).getIdentification())
                                        .putExtra("name",finalPersonData2List.get(i).getName())
                                        .putExtra("path",finalPersonData2List.get(i).getPath())
                                        .putExtra("voicetype",finalPersonData2List.get(i).getVoicetype())
                                        .putExtra("content",finalPersonData2List.get(i).getContent())
                                        .putExtra("mapRoute",finalPersonData2List.get(i).getMapRoute())
                                        .putExtra("receptionaction",finalPersonData2List.get(i).getReceptionAction()));
                                }
                        });
                        container.addView(view);
                        vipGuideTaskAdapter.notifyDataSetChanged();
                        return view;
                }

                @Override
                public int getItemPosition(Object object) {
                        return POSITION_NONE;
                }
        };

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.ok_btn:
                                isShow = true;
                                Logger.e("VipGuideTaskManageActivity", "111111isshow" + isShow);
                                pagerAdapter.notifyDataSetChanged();
                                break;
                }
        }

        public void del(final int index){
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));

                HashMap<String, Object> paramsMap = new HashMap<String, Object>();
                paramsMap.put("vipType", "delRoute");//id
                paramsMap.put("identification", finalPersonData2List.get(index).getIdentification());

                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST +
                        ":7755/" + "routevipGuide", paramsMap, new OkHttpUtils.OkHttpCallBack() {

                        @Override
                        public void onSuccess(String result) {

                                JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                if (strMsgBean.getRc() >= 0) {

                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        Logger.e("KnowVipActivity", "personData2List" + finalPersonData2List.size());
                                                        cancelDialog();
                                                        finalPersonData2List.remove(index);
                                                        pagerAdapter.notifyDataSetChanged();
                                                        isShow = false;
                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                isShow = true;
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                cancelDialog();
                                                ToastTools.newInstance(VipGuideTaskManageActivity.this).showText(getString(R.string.network_request_failed));
                                        }
                                });
                                Logger.e("KnowVipActivity", "onFailure" + "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/");
                        }
                });
        }

        private void cancelDialog() {
                if (dialogLoading != null) {
                        if (dialogLoading.isShowing()) {
                                dialogLoading.cancel();
                        }
                }
        }


        @Override
        protected void onPause() {
                cancelDialog();
                super.onPause();
        }

        public class VipGuideTaskAdapter extends BaseAdapter {

                List<VipPersonMapData> personData2List;

                LayoutInflater inflater;

                Context mContext;


                public VipGuideTaskAdapter(Context mContext, List<VipPersonMapData> personData2List) {
                        this.personData2List = personData2List;
                        this.mContext = mContext;
                        inflater = LayoutInflater.from(mContext);
                }

                @Override
                public int getCount() {
                        return personData2List.size();
                }

                @Override
                public Object getItem(int i) {
                        return personData2List.get(i);
                }

                @Override
                public long getItemId(int i) {
                        return i;
                }

                @Override
                public View getView(final int i, View convertView, ViewGroup viewGroup) {
                        final ViewHolder holder;
                        if (convertView == null) {
                                holder = new ViewHolder();
                                convertView = LayoutInflater.from(mContext).inflate(R.layout.vip_task_item, null);
                                holder.speechHead = (ImageView) convertView.findViewById(R.id.vip_task_path);
                                holder.speechName= (TextView) convertView.findViewById(R.id.vip_task_name);
                                holder.speechDel= (ImageView) convertView.findViewById(R.id.vip_task_del);
                                convertView.setTag(holder);
                        }
                        else {
                                holder = (ViewHolder) convertView.getTag();
                        }
                        holder.speechName.setText(personData2List.get(i).getName());

                        //圆形
                        GlideApp.with(mContext).clear(holder.speechHead);
                        GlideApp.with(mContext).asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST + "/temp/faces/"+personData2List.get(i).getPath())
                                .circleCrop()
                                .into(holder.speechHead);

                        if (VipGuideTaskManageActivity.isShow) {
                                holder.speechDel.setVisibility(View.VISIBLE);
                                holder.speechDel.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                                delIndex = nowIndex * 6 + i;
                                                del(delIndex);
                                        }
                                });
                        }
                        return convertView;
                }

                protected class ViewHolder {

                        public ImageView speechHead;

                        public ImageView speechDel;

                        public TextView speechName;

                }

        }


        @Override
        protected void onDestroy() {
                isShow = false;
                super.onDestroy();
        }
}
